#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <functional>
#include <unordered_map>
#include "log.hpp"

#define DEFAULT_PORT 8888
#define DEFAULT_IP "0.0.0.0"

using func_t = std::function<std::string(const std::string&)>;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};

Log log;
const int size = 1024;

class UdpServer
{
public:
    UdpServer(const uint16_t& port = DEFAULT_PORT, const std::string& ip = DEFAULT_IP)
        : _sockfd(0), _port(port), _ip(ip), _isRunning(false)
    {}

    void Init()
    {
        // 1. 创建 upd_socket
        // 2. Udp 的 socket 是全双工的，允许被同时读写的
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd == -1)
        {
            log(Fatal, "socket create error, sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
            exit(SOCKET_ERR);
        }
        log(Info, "socket create success, sockfd: %d", _sockfd);

        // 2. 绑定
        struct sockaddr_in local;
        bzero(&local, sizeof(local));   // 将指定空间全部初始化为0
        local.sin_family = AF_INET;     // 套接字结构体的前两个字节需要表明结构体的类型，也即通信的协议族：IPv4网络通信
        local.sin_port = htons(_port);  // 因为端口号是要通过网络发送给对方的，所以需要保证端口号是网络字节序
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());    // 1. string->uint32_t  2. uint32_t 必须为网络字节序
        local.sin_addr.s_addr = INADDR_ANY;  

        int n = bind(_sockfd, (const struct sockaddr*)&local, sizeof(local));   // 网络接口统一设计的体现
        if(n == -1) 
        {
            log(Fatal, "bind error, errno: %d, err string: %s\n", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log(Info, "socket bind success, errno: %d, err string: %s\n", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in client, const std::string clientip, uint16_t clientport)
    {
        auto iter = _online_user.find(clientip);
        if(iter == _online_user.end())
        {
            _online_user[clientip] = client;
            std::cout << "[" << clientip << ": " << clientport << "] add to online user." << std::endl;
        }
    }   
    
    void Broadcast(const std::string& info, const std::string clientip, uint16_t clientport)
    {
        for(const auto& user : _online_user)
        {
            std::string message = "[" + clientip + ": " + std::to_string(clientport) + "]# " + info;
            sendto(_sockfd, message.c_str(), message.size(), 0, (const sockaddr*)(&user.second), (socklen_t)sizeof(user.second));
        }
    }

    // void Run(func_t func)
    void Run()
    {   
        _isRunning = true;
        char inbuffer[size];
        while (_isRunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err string: %s\n", errno, strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);      // 网络字节序 --> 本地
            CheckUser(client, clientip, clientport);

            inbuffer[n] = 0;
            std::string info = inbuffer;
            Broadcast(info, clientip, clientport);
        }
        
    }

    ~UdpServer()
    {
        if(_sockfd > 0) 
            close(_sockfd);
    }

private:
    int _sockfd; // 网络文件描述符
    std::string _ip;
    uint16_t _port;
    bool _isRunning;
    std::unordered_map<std::string, struct sockaddr_in> _online_user;
};